//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_evaluate_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/org_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/org_eval_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/user_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/org_evaluate_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *OrgEvaluateApiImpl) CreateEvaluate(ctx context.Context, req *org_evaluate_api.CreateEvaluateRequest) (*org_evaluate_api.CreateEvaluateResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	if req.DepartMentId != "" {
		exist, err := org_dao.DepartMentDao.Exist(ctx, req.OrgId, req.DepartMentId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &org_evaluate_api.CreateEvaluateResponse{
				Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_DEPART_MENT,
				ErrMsg: "部门不存在",
			}, nil
		}
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == req.DepartMentId)) {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查目标是否存在
	count, err := org_eval_dao.TargetDao.CountById(ctx, req.OrgId, req.TargetIdList)
	if err != nil {
		return nil, err
	}
	if int(count) != len(req.TargetIdList) || count == 0 {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_TARGET,
			ErrMsg: "评估指标不存在",
		}, nil
	}
	//检查成员是否存在
	count, err = org_dao.MemberDao.CountById(ctx, req.OrgId, req.DepartMentId, req.MemberUserIdList)
	if err != nil {
		return nil, err
	}
	if int(count) != len(req.MemberUserIdList) || count < 3 {
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:   org_evaluate_api.CreateEvaluateResponse_CODE_NO_MEMBER,
			ErrMsg: "团队成员不存在",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	evaluateId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.EvaluateDao.Insert(sessCtx, &org_eval_dao.EvaluateInfoDbItem{
			EvaluateId:       evaluateId,
			OrgId:            req.OrgId,
			DepartMentId:     req.DepartMentId,
			EvaluateTitle:    req.EvaluateTitle,
			EvaluateDesc:     req.EvaluateDesc,
			MemberUserIdList: req.MemberUserIdList,
			TargetIdList:     req.TargetIdList,
			EvaluateState:    uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_DRAFT),
			CreateUserId:     sessionItem.UserId,
			CreateTime:       nowTime,
			UpdateUserId:     sessionItem.UserId,
			UpdateTime:       nowTime,
		})
		if err != nil {
			return nil, err
		}
		//计算评估指标关联数量
		for _, targetId := range req.TargetIdList {
			count, err := org_eval_dao.EvaluateDao.CountByTarget(sessCtx, req.OrgId, targetId)
			if err != nil {
				return nil, err
			}
			err = org_eval_dao.TargetDao.UpdateEvaluateCount(sessCtx, req.OrgId, targetId, count)
			if err != nil {
				return nil, err
			}
		}
		//更新部门评估计数
		if req.DepartMentId != "" {
			count, err := org_eval_dao.EvaluateDao.Count(sessCtx, req.OrgId, req.DepartMentId, false, "")
			if err != nil {
				return nil, err
			}
			err = org_dao.DepartMentDao.UpdateEvaluateCount(sessCtx, req.OrgId, req.DepartMentId, count)
			if err != nil {
				return nil, err
			}
		}
		return &org_evaluate_api.CreateEvaluateResponse{
			Code:       org_evaluate_api.CreateEvaluateResponse_CODE_OK,
			EvaluateId: evaluateId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.CreateEvaluateResponse), nil
}

func (apiImpl *OrgEvaluateApiImpl) UpdateBaseForEvaluate(ctx context.Context, req *org_evaluate_api.UpdateBaseForEvaluateRequest) (*org_evaluate_api.UpdateBaseForEvaluateResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	evaluateItem, err := org_eval_dao.EvaluateDao.Get(ctx, req.OrgId, req.EvaluateId)
	if err != nil {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_EVALUATE,
			ErrMsg: "评估不存在",
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == evaluateItem.DepartMentId)) {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//只能修改草案阶段数据
	if evaluateItem.EvaluateState != uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_DRAFT) {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查目标是否存在
	count, err := org_eval_dao.TargetDao.CountById(ctx, req.OrgId, req.TargetIdList)
	if err != nil {
		return nil, err
	}
	if int(count) != len(req.TargetIdList) || count == 0 {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_TARGET,
			ErrMsg: "评估指标不存在",
		}, nil
	}
	//检查成员是否存在
	count, err = org_dao.MemberDao.CountById(ctx, req.OrgId, evaluateItem.DepartMentId, req.MemberUserIdList)
	if err != nil {
		return nil, err
	}
	if int(count) != len(req.MemberUserIdList) || count < 3 {
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code:   org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_NO_MEMBER,
			ErrMsg: "团队成员不存在",
		}, nil
	}

	targetIdMap := map[string]bool{}
	for _, targetId := range evaluateItem.TargetIdList {
		targetIdMap[targetId] = true
	}
	for _, targetId := range req.TargetIdList {
		targetIdMap[targetId] = true
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.EvaluateDao.Update(sessCtx, req.OrgId, req.EvaluateId, req.EvaluateTitle, req.EvaluateDesc, req.MemberUserIdList, req.TargetIdList, sessionItem.UserId, nowTime)
		if err != nil {
			return nil, err
		}
		//计算评估指标关联数量
		for targetId := range targetIdMap {
			count, err := org_eval_dao.EvaluateDao.CountByTarget(sessCtx, req.OrgId, targetId)
			if err != nil {
				return nil, err
			}
			err = org_eval_dao.TargetDao.UpdateEvaluateCount(sessCtx, req.OrgId, targetId, count)
			if err != nil {
				return nil, err
			}
		}
		return &org_evaluate_api.UpdateBaseForEvaluateResponse{
			Code: org_evaluate_api.UpdateBaseForEvaluateResponse_CODE_OK,
		}, nil
	})

	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.UpdateBaseForEvaluateResponse), nil
}

// linksaas://comment/AwhxA8CheuuLFhrqMmWZx
func (apiImpl *OrgEvaluateApiImpl) UpdateStateForEvaluate(ctx context.Context, req *org_evaluate_api.UpdateStateForEvaluateRequest) (*org_evaluate_api.UpdateStateForEvaluateResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	evaluateItem, err := org_eval_dao.EvaluateDao.Get(ctx, req.OrgId, req.EvaluateId)
	if err != nil {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_NO_EVALUATE,
			ErrMsg: "评估不存在",
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == evaluateItem.DepartMentId)) {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	//检查状态转换
	wrongState := false
	if evaluateItem.EvaluateState == uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_DRAFT) {
		if req.State != org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_EVALUATE {
			wrongState = true
		}
	} else if evaluateItem.EvaluateState == uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_EVALUATE) {
		if req.State != org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_FINISH {
			wrongState = true
		}
	} else if evaluateItem.EvaluateState == uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_FINISH) {
		if req.State != org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_EVALUATE {
			wrongState = true
		}
	}
	if wrongState {
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code:   org_evaluate_api.UpdateStateForEvaluateResponse_CODE_WRONG_STATE,
			ErrMsg: "错误的新状态",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.EvaluateDao.UpdateState(sessCtx, req.OrgId, req.EvaluateId, uint32(req.State), sessionItem.UserId, nowTime)
		if err != nil {
			return nil, err
		}
		//从草稿到可投票状态，自动创建结果记录
		if evaluateItem.EvaluateState == uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_DRAFT) && req.State == org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_EVALUATE {
			for _, memberUserId := range evaluateItem.MemberUserIdList {
				for _, targetId := range evaluateItem.TargetIdList {
					err = org_eval_dao.ResultScoreDao.Insert(sessCtx, &org_eval_dao.ResultScoreDbItem{
						OrgId:        req.OrgId,
						EvaluateId:   req.EvaluateId,
						MemberUserId: memberUserId,
						TargetId:     targetId,
						TotalScore:   0,
					})
					if err != nil {
						return nil, err
					}
				}
			}
		}
		return &org_evaluate_api.UpdateStateForEvaluateResponse{
			Code: org_evaluate_api.UpdateStateForEvaluateResponse_CODE_OK,
		}, nil
	})

	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.UpdateStateForEvaluateResponse), nil
}

func (apiImpl *OrgEvaluateApiImpl) ListEvaluate(ctx context.Context, req *org_evaluate_api.ListEvaluateRequest) (*org_evaluate_api.ListEvaluateResponse, error) {
	emptyList := []*org_evaluate_api.EvaluateInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.ListEvaluateResponse{
			Code:         org_evaluate_api.ListEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg:       "会话不存在",
			EvaluateList: emptyList,
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.ListEvaluateResponse{
			Code:         org_evaluate_api.ListEvaluateResponse_CODE_NO_ORG,
			ErrMsg:       "组织不存在",
			EvaluateList: emptyList,
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.ListEvaluateResponse{
			Code:         org_evaluate_api.ListEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg:       "没有权限",
			EvaluateList: emptyList,
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || selfMemberItem.MemberPermInfo.ViewAllEvaluate ||
		selfMemberItem.ParentDepartMentId == req.DepartMentId) {
		return &org_evaluate_api.ListEvaluateResponse{
			Code:         org_evaluate_api.ListEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg:       "没有权限",
			EvaluateList: emptyList,
		}, nil
	}

	if req.FilterMemberUserId {
		count, err := org_dao.MemberDao.CountById(ctx, req.OrgId, req.DepartMentId, []string{req.MemberUserId})
		if err != nil {
			return nil, err
		}
		if count == 0 {
			return &org_evaluate_api.ListEvaluateResponse{
				Code:         org_evaluate_api.ListEvaluateResponse_CODE_NO_MEMBER,
				ErrMsg:       "团队成员不存在",
				EvaluateList: emptyList,
			}, nil
		}
	}

	//列出数据
	evaluateCount, err := org_eval_dao.EvaluateDao.Count(ctx, req.OrgId, req.DepartMentId, req.FilterMemberUserId, req.MemberUserId)
	if err != nil {
		return nil, err
	}
	evaluateItemList, err := org_eval_dao.EvaluateDao.List(ctx, req.OrgId, req.DepartMentId, req.FilterMemberUserId, req.MemberUserId, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//补全用户信息
	userIdList := []string{}
	evaluateIdList := []string{}
	for _, evaluateItem := range evaluateItemList {
		evaluateIdList = append(evaluateIdList, evaluateItem.EvaluateId)
		userIdList = append(userIdList, evaluateItem.MemberUserIdList...)
		userIdList = append(userIdList, evaluateItem.CreateUserId)
		userIdList = append(userIdList, evaluateItem.UpdateUserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//列出评估结果
	resultScoreItemList, err := org_eval_dao.ResultScoreDao.List(ctx, req.OrgId, evaluateIdList)
	if err != nil {
		return nil, err
	}
	resultScoreMap := map[string]uint32{}
	for _, resultScoreItem := range resultScoreItemList {
		resultScoreMap[resultScoreItem.ResultId] = resultScoreItem.TotalScore
	}
	//列出投票信息
	voteIdList, err := org_eval_dao.VoteScoreDao.DistinceVoteId(ctx, req.OrgId, evaluateIdList)
	if err != nil {
		return nil, err
	}
	voteIdMap := map[string]bool{}
	for _, voteId := range voteIdList {
		voteIdMap[voteId] = true
	}
	//列出所有投票目标
	targetItemList, err := org_eval_dao.TargetDao.List(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	targetNameMap := map[string]string{}
	for _, targetItem := range targetItemList {
		targetNameMap[targetItem.TargetId] = targetItem.TargetName
	}
	//生成数据
	evaluateList := []*org_evaluate_api.EvaluateInfo{}
	for _, evaluateItem := range evaluateItemList {
		evaluateInfo := apiImpl.convertToEvaluate(evaluateItem, userItemMap, resultScoreMap, voteIdMap, targetNameMap)
		if orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == req.DepartMentId) {
			evaluateInfo.UserPerm.CanUpdate = true
			evaluateInfo.UserPerm.CanRemove = true
			evaluateInfo.UserPerm.CanView = true
		}
		for _, memberUserId := range evaluateItem.MemberUserIdList {
			if memberUserId == sessionItem.UserId {
				evaluateInfo.UserPerm.CanView = true
			}
		}

		evaluateList = append(evaluateList, evaluateInfo)
	}

	return &org_evaluate_api.ListEvaluateResponse{
		Code:         org_evaluate_api.ListEvaluateResponse_CODE_OK,
		TotalCount:   evaluateCount,
		EvaluateList: evaluateList,
	}, nil
}

func (apiImpl *OrgEvaluateApiImpl) convertToEvaluate(evaluateItem *org_eval_dao.EvaluateInfoDbItem, userItemMap map[string]*user_dao.UserInfoDbItem,
	resultScoreMap map[string]uint32, voteIdMap map[string]bool, targetNameMap map[string]string) *org_evaluate_api.EvaluateInfo {
	retItem := evaluateItem.ToEvaluateInfo()
	memberList := []*org_evaluate_api.EvaluateMemberInfo{}
	for _, memberUserId := range evaluateItem.MemberUserIdList {
		memberInfo := &org_evaluate_api.EvaluateMemberInfo{
			MemberUserId: memberUserId,
			ScoreList:    []*org_evaluate_api.EvaluateTargetScore{},
			HasEvaluate:  false,
		}
		userItem, ok := userItemMap[memberUserId]
		if ok {
			memberInfo.MemberDisplayName = userItem.BasicInfo.DisplayName
			memberInfo.MemberLogoUri = userItem.BasicInfo.LogoUri
		}
		if len(evaluateItem.TargetIdList) > 0 {
			voteId := org_eval_dao.VoteScoreDao.GenVoteId(evaluateItem.EvaluateId, memberUserId, memberUserId, evaluateItem.TargetIdList[0])
			if evaluateItem.EvaluateState != uint32(org_evaluate_api.EVALUATE_STATE_EVALUATE_STATE_DRAFT) {
				memberInfo.HasEvaluate = voteIdMap[voteId]
			}
		}
		for _, targetId := range evaluateItem.TargetIdList {
			resultId := org_eval_dao.ResultScoreDao.GenResultId(evaluateItem.EvaluateId, memberUserId, targetId)
			memberInfo.ScoreList = append(memberInfo.ScoreList, &org_evaluate_api.EvaluateTargetScore{
				TargetId:   targetId,
				TargetName: targetNameMap[targetId],
				Score:      resultScoreMap[resultId],
			})
		}
		memberList = append(memberList, memberInfo)
	}
	retItem.MemberList = memberList
	createUser, ok := userItemMap[evaluateItem.CreateUserId]
	if ok {
		retItem.CreateDisplayName = createUser.BasicInfo.DisplayName
		retItem.CreateLogoUri = createUser.BasicInfo.LogoUri
	}
	updateUser, ok := userItemMap[evaluateItem.UpdateUserId]
	if ok {
		retItem.UpdateDisplayName = updateUser.BasicInfo.DisplayName
		retItem.UpdateLogoUri = updateUser.BasicInfo.LogoUri
	}
	return retItem
}

func (apiImpl *OrgEvaluateApiImpl) GetEvaluate(ctx context.Context, req *org_evaluate_api.GetEvaluateRequest) (*org_evaluate_api.GetEvaluateResponse, error) {
	emptyInfo := &org_evaluate_api.EvaluateInfo{
		MemberList: []*org_evaluate_api.EvaluateMemberInfo{},
		UserPerm:   &org_evaluate_api.UserPerm{},
	}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.GetEvaluateResponse{
			Code:     org_evaluate_api.GetEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			Evaluate: emptyInfo,
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.GetEvaluateResponse{
			Code:     org_evaluate_api.GetEvaluateResponse_CODE_NO_ORG,
			ErrMsg:   "组织不存在",
			Evaluate: emptyInfo,
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.GetEvaluateResponse{
			Code:     org_evaluate_api.GetEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			Evaluate: emptyInfo,
		}, nil
	}

	evaluateItem, err := org_eval_dao.EvaluateDao.Get(ctx, req.OrgId, req.EvaluateId)
	if err != nil {
		return &org_evaluate_api.GetEvaluateResponse{
			Code:     org_evaluate_api.GetEvaluateResponse_CODE_NO_EVALUATE,
			ErrMsg:   "评估不存在",
			Evaluate: emptyInfo,
		}, nil
	}
	if !(orgItem.OwnerUserId == sessionItem.UserId || selfMemberItem.MemberPermInfo.ViewAllEvaluate ||
		selfMemberItem.ParentDepartMentId == evaluateItem.DepartMentId) {
		return &org_evaluate_api.GetEvaluateResponse{
			Code:     org_evaluate_api.GetEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			Evaluate: emptyInfo,
		}, nil
	}

	//补全用户信息
	userIdList := []string{}
	userIdList = append(userIdList, evaluateItem.MemberUserIdList...)
	userIdList = append(userIdList, evaluateItem.CreateUserId)
	userIdList = append(userIdList, evaluateItem.UpdateUserId)

	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//列出评估结果
	resultScoreItemList, err := org_eval_dao.ResultScoreDao.List(ctx, req.OrgId, []string{req.EvaluateId})
	if err != nil {
		return nil, err
	}
	resultScoreMap := map[string]uint32{}
	for _, resultScoreItem := range resultScoreItemList {
		resultScoreMap[resultScoreItem.ResultId] = resultScoreItem.TotalScore
	}
	//列出投票信息
	voteIdList, err := org_eval_dao.VoteScoreDao.DistinceVoteId(ctx, req.OrgId, []string{req.EvaluateId})
	if err != nil {
		return nil, err
	}
	voteIdMap := map[string]bool{}
	for _, voteId := range voteIdList {
		voteIdMap[voteId] = true
	}
	//列出所有投票目标
	targetItemList, err := org_eval_dao.TargetDao.List(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	targetNameMap := map[string]string{}
	for _, targetItem := range targetItemList {
		targetNameMap[targetItem.TargetId] = targetItem.TargetName
	}
	//生成结果
	evaluateInfo := apiImpl.convertToEvaluate(evaluateItem, userItemMap, resultScoreMap, voteIdMap, targetNameMap)
	if orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == evaluateItem.DepartMentId) {
		evaluateInfo.UserPerm.CanUpdate = true
		evaluateInfo.UserPerm.CanRemove = true
		evaluateInfo.UserPerm.CanView = true
	}

	for _, memberUserId := range evaluateItem.MemberUserIdList {
		if memberUserId == sessionItem.UserId {
			evaluateInfo.UserPerm.CanView = true
		}
	}
	return &org_evaluate_api.GetEvaluateResponse{
		Code:     org_evaluate_api.GetEvaluateResponse_CODE_OK,
		Evaluate: evaluateInfo,
	}, nil
}

func (apiImpl *OrgEvaluateApiImpl) RemoveEvaluate(ctx context.Context, req *org_evaluate_api.RemoveEvaluateRequest) (*org_evaluate_api.RemoveEvaluateResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code:   org_evaluate_api.RemoveEvaluateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code:   org_evaluate_api.RemoveEvaluateResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code:   org_evaluate_api.RemoveEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	evaluateItem, err := org_eval_dao.EvaluateDao.Get(ctx, req.OrgId, req.EvaluateId)
	if err != nil { //没有记录
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code: org_evaluate_api.RemoveEvaluateResponse_CODE_OK,
		}, nil
	}
	if !(orgItem.OwnerUserId == sessionItem.UserId || (selfMemberItem.MemberPermInfo.ManageDepartMentEvaluate && selfMemberItem.ParentDepartMentId == evaluateItem.DepartMentId)) {
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code:   org_evaluate_api.RemoveEvaluateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.EvaluateDao.Remove(sessCtx, req.OrgId, req.EvaluateId)
		if err != nil {
			return nil, err
		}
		err = org_eval_dao.ResultScoreDao.RemoveByEvaluate(sessCtx, req.OrgId, req.EvaluateId)
		if err != nil {
			return nil, err
		}
		err = org_eval_dao.VoteScoreDao.RemoveByEvaluate(sessCtx, req.OrgId, req.EvaluateId)
		if err != nil {
			return nil, err
		}
		for _, targetId := range evaluateItem.TargetIdList {
			count, err := org_eval_dao.EvaluateDao.CountByTarget(sessCtx, req.OrgId, targetId)
			if err != nil {
				return nil, err
			}
			err = org_eval_dao.TargetDao.UpdateEvaluateCount(sessCtx, req.OrgId, targetId, count)
			if err != nil {
				return nil, err
			}
		}
		//更新部门评估计数
		if evaluateItem.DepartMentId != "" {
			count, err := org_eval_dao.EvaluateDao.Count(sessCtx, req.OrgId, evaluateItem.DepartMentId, false, "")
			if err != nil {
				return nil, err
			}
			err = org_dao.DepartMentDao.UpdateEvaluateCount(sessCtx, req.OrgId, evaluateItem.DepartMentId, count)
			if err != nil {
				return nil, err
			}
		}
		return &org_evaluate_api.RemoveEvaluateResponse{
			Code: org_evaluate_api.RemoveEvaluateResponse_CODE_OK,
		}, nil
	})

	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.RemoveEvaluateResponse), nil
}
